﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;

namespace up6.db.utils
{
    public class FileTool
    {
        /// <summary>
        /// 以线程安全方式向文件添加数据
        /// </summary>
        /// <param name="file"></param>
        /// <param name="data"></param>
        public static void appendSafe(string file, string data)
        {
            bool writeAcc = false;
            while (!writeAcc)
            {
                try
                {
                    FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None);
                    byte[] arr = Encoding.UTF8.GetBytes(data);
                    fs.Write(arr, 0, arr.Length);
                    fs.Flush();
                    fs.Close();
                    writeAcc = true;
                    break;
                }
                catch (IOException e)
                {
                    Thread.Sleep(1000);
                }
                finally { }
            }
        }

        /// <summary>
        /// 添加一行
        /// </summary>
        /// <param name="file"></param>
        /// <param name="data"></param>
        public static void appendLine(string file, string data)
        {
            bool writeAcc = false;
            while (!writeAcc)
            {
                try
                {
                    FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None);
                    byte[] arr = Encoding.UTF8.GetBytes(data);
                    fs.Write(arr, 0, arr.Length);
                    //写入换行符
                    arr = Encoding.UTF8.GetBytes("\n");
                    fs.Write(arr,0,arr.Length);

                    fs.Flush();
                    fs.Close();
                    writeAcc = true;
                    break;
                }
                catch (IOException e)
                {
                    Thread.Sleep(1000);
                }
                finally { }
            }
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string extension(string fileName)
        {
            if(fileName.IndexOf('.')==-1) return String.Empty;
            var exts = fileName.Split('.');
            return exts.Length<2?string.Empty:exts[exts.Length - 1];
        }
    }
}